package com.zprmb.udzt;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;

import com.zprmb.udzt.ListImageDirPopupWindow.OnImageDirSelected;
import com.zprmb.udzt.adapter.PictureAdapter;
import com.zprmb.udzt.http.AjaxCallBack;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.http.FinalHttp;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.ImageUtil;
import com.zprmb.udzt.util.ToastUtil;

public class SelectImageActivity extends BaseActivity implements
		OnClickListener, OnImageDirSelected {
	private RelativeLayout rl_selectImage_back;
	private GridView gridview;
	private ContentResolver mContentResolver;
	private ImageFloder imageAll, currentImageFolder;
	private PictureAdapter adapter;
	public static final String INTENT_SELECTED_PICTURE = "intent_selected_picture";
	/**
	 * 临时的辅助类，用于防止同一个文件夹的多次扫描
	 */
	private HashMap<String, Integer> tmpDir = new HashMap<String, Integer>();
	private ArrayList<ImageFloder> mDirPaths = new ArrayList<ImageFloder>();
	private Button btn_select;
	private ListImageDirPopupWindow mListImageDirPopupWindow;
	private int mScreenHeight;
	private Bitmap map = null;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				initListDirPopupWindw();
				break;
			case 2:
				adapter = new PictureAdapter(SelectImageActivity.this,
						currentImageFolder);
				gridview.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			}
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.selectimage_activity);
		mContentResolver = getContentResolver();
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		mScreenHeight = outMetrics.heightPixels;
		initView();
	}

	private void initView() {
		imageAll = new ImageFloder();
		imageAll.setDir("/所有图片");
		currentImageFolder = imageAll;
		mDirPaths.add(imageAll);
		rl_selectImage_back = (RelativeLayout) findViewById(R.id.rl_selectImage_back);
		rl_selectImage_back.setOnClickListener(this);
		gridview = (GridView) findViewById(R.id.gridview);
		adapter = new PictureAdapter(this, currentImageFolder);
		gridview.setAdapter(adapter);
		btn_select = (Button) findViewById(R.id.btn_select);
		btn_select.setOnClickListener(this);
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {
					ImageUtil.openCameraImage(SelectImageActivity.this);
				} else {
					String str = (String) parent.getItemAtPosition(position);
					/*BitmapFactory.Options options = new BitmapFactory.Options();
					options.inJustDecodeBounds = true;
					Bitmap bitmap = BitmapFactory.decodeFile(str, options);
					options.inJustDecodeBounds = false;
					options.inSampleSize = cal*/
					map = getimage(str);
					Updata(str, null);
					/*
					 * Intent data = new Intent(); data.putExtra("123", str);
					 * setResult(RESULT_OK, data); finish();
					 */
				}
			}
		});
		getThumbnail();
	}

	private Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 240f;// 这里设置高度为800f
		float ww = 160f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		// 裁剪图片后结果
		case ImageUtil.CROP_IMAGE:
			Cursor cursor = null;
			cursor = getContentResolver().query(ImageUtil.cropImageUri, null,
					null, null, null);
			cursor.moveToFirst();
			Updata("", cursor);// 这里就是上传的封装。。可以直接复制过去用。。。
			break;
		// 拍照获取图片
		case ImageUtil.GET_IMAGE_BY_CAMERA:
			if (resultCode == RESULT_OK) {
				ImageUtil.cropImage(this, ImageUtil.imageUriFromCamera);
			}
			break;
		case ImageUtil.GET_IMAGE_FROM_PHONE:
			if (ImageUtil.imageUriFromCamera != null) {
				ImageUtil.cropImage(this, ImageUtil.imageUriFromCamera);
				break;
			}
			break;
		}
	}

	private void Updata(String str, Cursor cursor) {
		/*
		 * Cursor cursor = null; SharedPreferences sp =
		 * getSharedPreferences("config", MODE_PRIVATE); cursor =
		 * getContentResolver().query(ImageUtil.cropImageUri, null, null, null,
		 * null); cursor.moveToFirst();
		 */
		/*
		 * Editor editor = sp.edit(); editor.putString("nativeImage",
		 * cursor.getString(1)); editor.commit(); finish();
		 */
		AjaxParams params = new AjaxParams();
		try {
			if (str.equals("")) {
				System.out.println("das=" + cursor.getString(1));
				params.put("file", new File(cursor.getString(1)));
			} else {
				//System.out.println("dasdsadas=" + str);
				//ToastUtil.showToast(SelectImageActivity.this, str);
				String sdpath = Environment.getExternalStorageDirectory() + "/xmrxbbt/";
				File filej = new File(sdpath);
				if (!filej.exists()) {
					filej.mkdirs();	
				}
				File file = new File(sdpath + str.substring(str.length()-10, str.length())+".jpg");// 将要保存图片的路径
				try {
					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(file));
					map.compress(Bitmap.CompressFormat.JPEG, 100, bos);
					bos.flush();
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				params.put("file", file);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		FinalHttp fh = new FinalHttp();
		fh.addHeader("token", getShare().getString("token", ""));
		fh.post(Constant.URL + "apiAccount/uploadPicture", params,
				new AjaxCallBack<Object>() {
					public void onStart() {
						super.onStart();
						showLoding();
						// ToastUtil.showToast(SelectImageActivity.this, "开始了");
					}
					public void onSuccess(Object t) {
						super.onSuccess(t);
						String json = (String) t;
						closeLoding();
						System.out.println("SelectImageActivity="+json);
						ToastUtil.showToast(SelectImageActivity.this, "头像上传成功");
						SelectImageActivity.this.finish();
					}
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						closeLoding();
						ToastUtil.showToast(SelectImageActivity.this, "头像上传失败");
					}
				});
	}

	/**
	 * 得到缩略图
	 */
	private void getThumbnail() {
		Cursor mCursor = mContentResolver.query(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				new String[] { MediaStore.Images.ImageColumns.DATA }, "", null,
				MediaStore.MediaColumns.DATE_ADDED + " DESC");
		// Log.e("TAG", mCursor.getCount() + "");
		if (mCursor.moveToFirst()) {
			int _date = mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
			do {
				// 获取图片的路径
				String path = mCursor.getString(_date);
				Log.e("TAG", path);
				imageAll.images.add(new ImageItem(path));
				// 获取该图片的父路径名
				File parentFile = new File(path).getParentFile();
				if (parentFile == null) {
					continue;
				}
				ImageFloder imageFloder = null;
				String dirPath = parentFile.getAbsolutePath();
				if (!tmpDir.containsKey(dirPath)) {
					// 初始化imageFloder
					imageFloder = new ImageFloder();
					imageFloder.setDir(dirPath);
					imageFloder.setFirstImagePath(path);
					mDirPaths.add(imageFloder);
					// Log.d("zyh", dirPath + "," + path);
					tmpDir.put(dirPath, mDirPaths.indexOf(imageFloder));
				} else {
					imageFloder = mDirPaths.get(tmpDir.get(dirPath));
				}
				imageFloder.images.add(new ImageItem(path));
			} while (mCursor.moveToNext());
		}
		mCursor.close();
		for (int i = 0; i < mDirPaths.size(); i++) {
			// ImageFloder f = mDirPaths.get(i);
			// Log.d("zyh", i + "-----" + f.getName() + "---" +
			// f.images.size());
		}
		handler.sendEmptyMessage(1);
		tmpDir = null;
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_selectImage_back:
			finish();
			break;
		case R.id.btn_select:
			mListImageDirPopupWindow.setAnimationStyle(R.style.anim_popup_dir);
			mListImageDirPopupWindow.showAsDropDown(btn_select, 0, 0);
			// 设置背景颜色变暗
			WindowManager.LayoutParams lp = getWindow().getAttributes();
			lp.alpha = .3f;
			getWindow().setAttributes(lp);
			break;
		}
	}

	/**
	 * 初始化展示文件夹的popupWindw
	 */
	private void initListDirPopupWindw() {
		mListImageDirPopupWindow = new ListImageDirPopupWindow(
				LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
				mDirPaths, LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.select_list_dir, null));

		mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener() {
			public void onDismiss() {
				// 设置背景颜色变暗
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = 1.0f;
				getWindow().setAttributes(lp);
			}
		});
		// 设置选择文件夹的回调
		mListImageDirPopupWindow.setOnImageDirSelected(this);
	}

	public void selected(ImageFloder floder) {
		btn_select.setText(floder.getName());
		currentImageFolder = floder;
		handler.sendEmptyMessage(2);
		mListImageDirPopupWindow.dismiss();
	}
	
	protected void onDestroy() {
		super.onDestroy();
		map = null;
	}
}
